import fl from '@king-fisher/falcon';
import bridge from '@king-fisher/bridge';
import Apis from '@king-fisher/apis';
import config from '../config/config.json';
import { isWeb } from '@king-fisher/env';

/**
 * 协议跳转，带状态栏的时间等内容
 * @param url  跳转地址
 * @returns
 */

export function jumpByUrl({ name, query }) {
  let url = '';
  let params = '';
  if (query) {
    params = Object.keys(query).reduce((acc, cur, index) => {
      acc += `${index === 0 ? '?' : '&'}${cur}=${query[cur]}`;
      return acc;
    }, '');
  }
  // 目前@king-fisher/env有问题，在安卓端判断不出来在小程序
  if (isWeb && process.env.NODE_ENV === 'development') {
    const route = config.pages.find(item => item.name === name);
    url = route.path + params;
    location.href = url;
  } else {
    url = name + params;
    fl.navigateTo({ url });
  }
}

export function getUrlSearch(getKey) {
  let name, value;
  const obj = {};
  let str = location.href; //取得整个地址栏
  let num = str.indexOf('?');
  str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]

  var arr = str.split('&'); //各个参数放到数组里
  for (var i = 0; i < arr.length; i++) {
    num = arr[i].indexOf('=');
    if (num > 0) {
      name = arr[i].substring(0, num);
      value = arr[i].substr(num + 1).replace('#/', '');
      obj[name] = value;
    }
  }
  if (getKey) {
    return obj[getKey];
  } else {
    return obj;
  }
}

export function jumpToFenshi(stockCode, marketId, stockName) {
  if (!stockCode || typeof stockCode !== 'string') {
    return;
  }
  bridge.callNativeHandlerAsync(
    'jumpNativePage',
    [
      `client.html?action=ymtz^webid=2205^stockcode=${stockCode}^marketid=${marketId}^stockname=${stockName}`,
    ],
    () => {}
  );
}

const DELAY = 300;
export function debounce(func, intervalTime = DELAY) {
  let timeId = null;
  return function (...args) {
    if (timeId) {
      clearTimeout(timeId);
    }
    timeId = setTimeout(() => {
      timeId = null;
      func.apply(this, args);
    }, intervalTime);
  };
}
export const throttle = (func, limit = DELAY) => {
  let inThrottle;

  return function () {
    const args = arguments;
    const context = this;

    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
};
export function getCurrentDate() {
  const dateParam = new Date();
  const year = dateParam.getFullYear(); //得到年份
  const month = dateParam.getMonth() + 1; //得到月份
  const date = dateParam.getDate(); //得到日期
  return `${year}-${month}-${date}`;
}

export function changeStringIntoDate(str, length) {
  if (str && str.length === 8) {
    const year = str.substring(0, 4);
    const month = str.substring(4, 6);
    const date = str.substring(6, 8);
    // 定义不同的日期格式化策略
    const strategies = {
      1: date,
      2: `${year}-${month}`,
      '-1': year,
      default: `${year}-${month}-${date}`,
    };
    return strategies[length] || strategies.default;
  } else {
    return '--';
  }
}

export const previousPeriod = '较上期';
// 将’--‘变成无变化
export function formatChgStringScore(chg, num = 0) {
  const score = formatChgString(chg, num);
  return score === '--' ? '无变化' : score;
}

export function formatChgString(chg, num = 0) {
  const str = chg;
  if (str) {
    const newChg = str.toString().replaceAll('-', '');
    const newStr = Number(newChg).toFixed(num);
    return newStr;
  } else {
    return '--';
  }
}

/**
 * 判断是否为Null
 *  @param {unknown} val 任意类型
 *  @returns {Boolean}
 */
function isNull(val) {
  const target = typeof val === 'object' ? Object.prototype.toString.call(val) : `${val}`;
  return /null|undefined|nan|^\s*$/i.test(target);
}

export function formatChgStringColor(chg) {
  const str = chg;
  if (str && Number(str) > 0) {
    return 'red';
  } else if (str && Number(str) < 0) {
    return 'green';
  } else {
    return 'black';
  }
}

// 处理字符串型的数字，正数添加添加正号
export function formatNumber(str) {
  if (isNull(str) || str === '--') {
    return {
      sign: '',
      abs: '--',
      num: '--',
      signStr: '--',
      colorClass: 'grey',
    };
  }
  let sign = '';
  let signStr = str;
  let abs = 0;
  let num = 0;
  let colorClass = 'grey';
  num = parseFloat(str);
  if (num > 0) {
    sign = '+';
    signStr = `+${str}`;
    colorClass = 'red';
  } else if (num < 0) {
    sign = '-';
    colorClass = 'green';
  } else {
    signStr = str.replace(/0+[.]?0*/, '0.00');
  }
  abs = Math.abs(num);
  return {
    abs: isNaN(abs) ? '' : abs,
    num: isNaN(num) ? 0.0 : num,
    sign,
    signStr,
    colorClass,
  };
}

//获得当前背景主题
export function getAppTheme() {
  try {
    return fl.getAppBaseInfo();
  } catch (error) {
    errorReport({
      name: `获取当前背景主题客户端协议getAppBaseInfo错误${error.name}`,
      message: error.message,
      stack: error.stack,
      category: 'js',
    });
  }
}

//监听系统主题改变事件。
export function onAppThemeChange(func) {
  try {
    return fl.onThemeChange(func);
  } catch (error) {
    errorReport({
      name: `监听当前背景主题变化客户端协议onThemeChange错误${error.name}`,
      message: error.message,
      stack: error.stack,
      category: 'js',
    });
  }
}

//判断日期的季度
export function getDateQuarter(str) {
  if (str && str.length === 8) {
    const month = Number(str.substring(4, 6));
    return Math.floor(month % 3 === 0 ? month / 3 : month / 3 + 1);
  } else {
    return '--';
  }
}

//获取userid
export function getUserId() {
  var a = navigator.userAgent,
    b = a.indexOf('userid/');
  if (b > -1) {
    var c = a.substr(b + 7);
    return (c = c.split(' ')), c[0];
  }
  return 0;
}

export function setCookie() {
  return new Promise((resolve, reject) => {
    const iosUserId = getUserId();
    if (iosUserId) {
      resolve(iosUserId);
    } else {
      fl.getHostUserInfo({
        success: res => {
          resolve(res.userId);
        },
        fail: error => {
          errorReport({
            name: `获取userid客户端协议getHostUserInfo错误${error.name}`,
            message: error.message,
            stack: error.stack,
            category: 'js',
          });
          resolve('0');
        },
      });
    }
  });
}

export function caniuse(apiName, fn) {
  if (fl.canIUse(apiName)) {
    fn();
  } else {
    errorReport({
      name: '版本过低',
      message: `${getUserId()}版本过低,版本是${window.getAppVersion()}`,
      stack: `${getUserId()}版本过低,版本是${window.getAppVersion()}`,
      category: 'js',
    });
    Apis.Toast.show('您的同花顺版本过低，请升级后重试！');
  }
}

// 错误上报
export function errorReport({ name, message, stack, category = 'ajax' }) {
  window.ClientMonitor.reportFrameErrors(
    {
      // 类型
      category,
      // 级别
      grade: 'Error',
    },
    {
      name,
      message,
      stack,
    }
  );
}

// 将科学计数法转成小数格式 -主要解决-7次方之后精度不准问题
export function transferToNumber(inputNumber) {
  if (isNaN(inputNumber)) {
    return inputNumber;
  }
  inputNumber = '' + inputNumber;
  inputNumber = parseFloat(inputNumber);
  // 转换为标准的科学计数法形式（字符串）
  const eformat = inputNumber.toExponential();
  // 分离出小数值和指数值
  const tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/);
  return inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]));
}

// 获取标题栏目状态栏vw高度
export function getHeaderInfoVw() {
  // 默认顶部状态栏高度
  const defaultStatusBarHeight = 88;
  // 屏幕宽度7.5rem
  const screenWidthRate = 7.5;
  let statusBarHeight = defaultStatusBarHeight;
  try {
    statusBarHeight = fl.getWindowInfo().statusBarHeight;
  } catch (error) {
    errorReport({
      name: `获取标题栏目状态栏vw高度客户端协议getWindowInfo错误${error.name}`,
      message: error.message,
      stack: error.stack,
      category: 'js',
    });
  }
  return {
    // 除以屏幕宽度，使高度单位为vw
    statusBarHeight: statusBarHeight / screenWidthRate,
    // 状态栏高度，单位为vw
    headerHeight: (statusBarHeight + defaultStatusBarHeight) / screenWidthRate,
  };
}

export function navigateBack() {
  // 目前@king-fisher/env有问题，在安卓端判断不出来在小程序
  if (isWeb && process.env.NODE_ENV === 'development') {
    window.history.back();
  } else {
    fl.navigateBack({ delta: 1 });
  }
}

export class DatePlus extends Date {
  constructor(args) {
    args ? super(args) : super();
  }
  format(fmt = 'yyyy-MM-dd hh:mm:ss') {
    const quarterlyMonths = 3;
    const o = {
      //月份
      'M+': this.getMonth() + 1,
      'd+': this.getDate(),
      'h+': this.getHours(),
      'm+': this.getMinutes(),
      's+': this.getSeconds(),
      'q+': Math.floor((this.getMonth() + quarterlyMonths) / quarterlyMonths),
      S: this.getMilliseconds(),
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        `${this.getFullYear()}`.substr(quarterlyMonths + 1 - RegExp.$1.length)
      );
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
        );
      }
    }
    return fmt;
  }
}
